package 数组题目.数组变换;

//生成螺旋矩阵
//https://leetcode.cn/problems/spiral-matrix-ii/description/
//给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
class 生成螺旋矩阵 {
    public int[][] generateMatrix(int n) {
        int[][] ans = new int[n][n];
        int top = 0;
        int bottom = n - 1;
        int left = 0;
        int right = n - 1;
        int nums = 1;
        while (nums <= n * n) {
            // 从左到右
            if (top <= bottom) {
                for (int i = left; i <= right; i++) {
                    ans[top][i] = nums;
                    nums++;
                }
                top++;
            }
            // 从上到下
            if (right >= left) {
                for (int i = top; i <= bottom; i++) {
                    ans[i][right] = nums;
                    nums++;
                }
                right--;
            }
            // 从右到左
            if (bottom >= top) {
                for (int i = right; i >= left; i--) {
                    ans[bottom][i] = nums;
                    nums++;
                }
                bottom--;
            }
            // 从下到上
            if (right >= left) {
                for (int i = bottom; i >= top; i--) {
                    ans[i][left] = nums;
                    nums++;
                }
                left++;
            }
        }
        return ans;
    }

//    public static void main(String[] args) {
//        Solution generateMatrix = new Solution();
//        int[][] matrix = generateMatrix.generateMatrix(3);
//        System.out.println(matrix);
//    }
}
